<?php


namespace app\api\controller;

use app\ApiController;
use app\common\library\ResultCode;
use app\common\library\Sms;
use app\common\library\Upload;
use Psr\SimpleCache\InvalidArgumentException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use app\common\model\system\User as UserModel;
use app\common\model\system\Reservation;
use app\common\model\system\UserThird;
use EasyWeChat\Factory;
use think\facade\Db;
use Webman\Event\Event;
use app\common\model\system\UserLog;
use app\common\model\system\Address;
use app\common\model\system\Porder;
use app\common\model\system\PointProduct;
use app\common\model\system\UserIntegralLog;
use app\common\model\system\RecseriveList;
use app\common\model\system\Recserive;
use app\common\model\system\SeriesType;
use app\common\model\system\Product;
use think\facade\Cache;
use app\common\model\system\Config;
use app\common\model\system\Kehu;
use app\common\model\system\Putorder;
use app\common\model\system\PutorderProduct;
use app\common\model\system\ProductLog;
use system\Random;
use think\Validate;


/**
 * API用户登录
 */
class User extends ApiController
{
    /**
     * 需要登录
     * @var bool
     */
    public bool $needLogin = true;

    /**
     * 非鉴权方法
     * @var array
     */
    public array $noNeedAuth = ['login', 'upload', 'mlogin', 'cate'];
    protected $config = [
        'statusArr' => [
            1 => '待管理员确认接单',
            2 => '待分配司机',
            3 => '待取货',
            4 => '待送货',
            5 => '待完成',
            6 => '已完成',
            7 => '已取消',
        ],
        'sendType' => [
            1 => '公司配送',
            2 => '自提',
            3 => '货拉拉',
            4 => '挂车'
        ]
    ];

    public function cate()
    {
        $leftArray = [];
        $mainArray = [];
        $seriestype = (new SeriesType())->where('status', 2)->order('sort desc')->field('id,title')->select();
        foreach ($seriestype as $series) {
            $leftArray[] = $series['title'];
            $mainArray[] = [
                'title' => $series['title'],
                'list' => (new Product())->field('id,title,series,types,images,price,codes,spec,remark,stock,detail')->where('types', $series['id'])->select()->each(function ($item) {
                    $item['number'] = 0;
                    $item['images'] = json_decode($item['images'], true);
                    return $item;
                })
            ];
        }
        return $this->apisuccess(['leftArray' => $leftArray, 'mainArray' => $mainArray], '获取成功');
    }

    public function editordergoods()
    {
        if (request()->isPost()) {
            $post = request()->post();
            $validate = (new Validate())->rule([
                'id' => 'require',
                'goods' => 'require'
            ]);
            $validate->message([
                'id.require' => '订单商品ID不能为空',
                'goods.require' => '商品数据不能为空',
            ]);
            if (!$validate->check($post)) {
                return $this->apierror([], $validate->getError(), 0);
            }
            if (request()->user->type != 1) {
                return $this->apierror([], '非管理员无操作权限', 0);
            }
            if (count($post['goods']) <= 0) {
                return $this->apierror([], '请选择商品', 0);
            }
            $totals = 0;
            foreach ($post['goods'] as $goods) {
                if (empty($goods['id'])) {
                    return $this->apierror([], '数据错误', 0);
                }
                if ($goods['number'] <= 0) {
                    return $this->apierror([], $goods['title'] . '未填写数量', 0);
                }
                $porder = (new PutorderProduct())->where(['goodsid' => $goods['id'], 'orderid' => $post['id']])->find();
                if (!empty($porder)) {
                    return $this->apierror([], '【' . $goods['title'] . '】产品已添加,请前往更改数量');
                }
                $totals += $goods['number'] * $goods['price'];
            }
            $order = (new Putorder())->where('id', $post['id'])->find();
            if (empty($order)) {
                return $this->apierror([], '订单不存在');
            }
            if ($order['status'] >= 6) {
                return $this->apierror([], '订单状态不可继续操作');
            }
            $update = ['id' => $post['id'], 'total' => ($order['total'] + $totals)];
            Db::startTrans();
            try {
                (new Putorder())->update($update);
                foreach ($post['goods'] as $goods) {
                    $goods['images'] = json_encode($goods['images'] ?? [], true);
                    $goods['orderid'] = $post['id'];
                    $goods['goodsid'] = $goods['id'];
                    unset($goods['id']);
                    (new PutorderProduct())->create($goods);
                    if ($order['status'] > 1) {
                        if ($order['type'] == 1) {
                            (new ProductLog())->ProductSkuEdit($goods['goodsid'], -$goods['number'], 1, '订单添加商品数量' . $order['id'] . '更改库存', request()->user->id);
                        } else {
                            (new ProductLog())->ProductSkuEdit($goods['goodsid'], $goods['number'], 1, '订单添加商品' . $order['id'] . '更改库存', request()->user->id);
                        }
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->apierror([], $e->getMessage());
            }
            return $this->apisuccess([], '操作成功', 0);
        }
    }

    public function editordernumber()
    {
        // 获取参数
        if (request()->isPost()) {
            $post = request()->post();
            $validate = (new Validate())->rule([
                'id' => 'require',
                'number' => 'require|gt:0|number'
            ]);
            $validate->message([
                'id.require' => '订单商品ID不能为空',
                'number.require' => '订单修改后商品数量不能为空',
                'number.gt' => '订单修改后商品数量必须大于0',
                'number.number' => '订单修改后商品数量必须为整数',
            ]);
            if (!$validate->check($post)) {
                return $this->apierror([], $validate->getError(), 0);
            }
            if (request()->user->type != 1) {
                return $this->apierror([], '非管理员无操作权限', 0);
            }
            $orderproduct = (new PutorderProduct())->where('id', $post['id'])->find();
            if (empty($orderproduct)) {
                return $this->apierror([], '选中订单商品不存在，请重试或刷新', 0);
            }
            if ($orderproduct['number'] == $post['number']) {
                return $this->apierror([], '商品数量没有改变');
            }
            $order = (new Putorder())->where('id', $orderproduct['orderid'])->find();
            if (empty($order)) {
                return $this->apierror([], '关联订单不存在');
            }
            if ($order['status'] >= 6) {
                return $this->apierror([], '订单状态不可继续操作');
            }
            $bgnumber = $post['number'] - $orderproduct['number'];
            $bgtotal = $bgnumber * $orderproduct['price'];
            $update = [
                'id' => $order['id'],
                'total' => $order['total'] + $bgtotal
            ];
            Db::startTrans();
            try {
                (new Putorder())->update($update);
                (new PutorderProduct())->update(['id' => $orderproduct['id'], 'number' => $post['number']]);
                //变更库存
                if ($order['status'] > 1) {
                    if ($order['type'] == 1) {
                        (new ProductLog())->ProductSkuEdit($orderproduct['goodsid'], -$bgnumber, 1, '变更商品数量' . $orderproduct['id'] . '更改库存', request()->user->id);
                    } else {
                        (new ProductLog())->ProductSkuEdit($orderproduct['goodsid'], $bgnumber, 1, '变更商品数量' . $orderproduct['id'] . '更改库存', request()->user->id);
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->apierror($e->getMessage());
            }
            return $this->apisuccess([], '操作成功', 0);
        }
    }

    public function orderproductdel()
    {
        // 获取参数
        if (request()->isPost()) {
            $post = request()->post();
            $validate = (new Validate())->rule([
                'id' => 'require',
            ]);
            $validate->message([
                'id.require' => '订单商品ID不能为空',
            ]);
            if (!$validate->check($post)) {
                return $this->apierror([], $validate->getError(), 0);
            }
            if (request()->user->type != 1) {
                return $this->apierror([], '非管理员无操作权限', 0);
            }
            $orderproduct = (new PutorderProduct())->where('id', $post['id'])->find();
            if (empty($orderproduct)) {
                return $this->apierror([], '选中订单商品不存在，请重试或刷新', 0);
            }
            $haveorder = (new PutorderProduct())->where('orderid', $orderproduct['orderid'])->count();
            if ($haveorder <= 1) {
                return $this->apierror([], '订单内必须保留一种商品,如需全部删除请取消订单', 0);
            }
            $order = (new Putorder())->where('id', $orderproduct['orderid'])->find();
            if (empty($order)) {
                return $this->apierror([], '关联订单不存在');
            }
            if ($order['status'] >= 6) {
                return $this->apierror([], '订单状态不可继续操作');
            }
            Db::startTrans();
            try {
                PutorderProduct::destroy($post['id']);
                //库存操作
                if ($order['status'] >= 2) {
                    $update = [
                        'id' => $order['id'],
                        'total' => $order['total'] - ($orderproduct['number'] * $orderproduct['price'])
                    ];
                    (new Putorder())->update($update);
                    if ($order['type'] == 1) {
                        (new ProductLog())->ProductSkuEdit($orderproduct['goodsid'], $orderproduct['number'], 1, '删除商品' . $orderproduct['id'] . '返还库存', request()->user->id);
                    } else {
                        (new ProductLog())->ProductSkuEdit($orderproduct['goodsid'], -$orderproduct['number'], 1, '退单类型删除商品' . $orderproduct['id'] . '扣除库存', request()->user->id);
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->apierror($e->getMessage());
            }
            return $this->apisuccess([], '操作成功', 0);
        }
    }

    public function getorderstatus()
    {
        if (request()->isPost()) {
            // 获取参数
            if (request()->isPost()) {
                $post = request()->post();
                $validate = (new Validate())->rule([
                    'id' => 'require',
                    'status' => 'require',
                ]);
                $validate->message([
                    'id.require' => 'ID不能为空',
                    'status.require' => '操作状态不能为空',
                ]);
                if (!$validate->check($post)) {
                    return $this->apierror([], $validate->getError(), 0);
                }
                $order = (new Putorder())->where('id', $post['id'])->find();
                switch ($post['status']) {
                    case '2':
                        if ($order['status'] != 1) {
                            return $this->apierror([], '订单状态不可确认', 0);
                        }
                        if (request()->user->type != 1) {
                            return $this->apierror([], '非管理员无确认权限', 0);
                        }
                        $post['confirm_time'] = time();
                        break;
                    case '3':
                        if (request()->user->type != 1) {
                            return $this->apierror([], '非管理员无分配司机权限', 0);
                        }
                        if ($order['status'] < 2 && $order['status'] >= 6) {
                            return $this->apierror([], '订单状态不可再更改司机', 0);
                        }
                        if ($post['send_type'] == 1 && empty($post['ouser_id'])) {
                            return $this->apierror([], '请选择司机人员', 0);
                        }
                        if ($post['send_type'] > 1 && empty($post['send_mobile'])) {
                            return $this->apierror([], '请填写配送人员信息', 0);
                        }
                        //更改司机订单状态不改变
                        if ($order['status'] >= 3) {
                            $post['status'] = $order['status'];
                        }
                        $post['allocate_time'] = time();
                        break;
                    case '4':
                        if ($order['status'] != 3) {
                            return $this->apierror([], '订单状态不可确认已取货', 0);
                        }
                        $post['pickup_time'] = time();
                        break;
                    case '5':
                        if ($order['status'] != 4 && $order['status'] != 5) {
                            return $this->apierror([], '订单状态无法拍照更改状态', 0);
                        }
                        if (empty($post['images'])) {
                            return $this->apierror([], '请上传送达图片', 0);
                        }
                        if (count($post['images']) < 1) {
                            return $this->apierror([], '请上传至少一张送达图片', 0);
                        }
                        $post['images'] = json_encode($post['images'], true);
                        //更改司机订单状态不改变
                        if ($order['status'] > 4) {
                            $post['status'] = $order['status'];
                        }
                        $post['delivery_time'] = time();
                        break;
                    case '6':
                        if ($order['status'] != 5) {
                            return $this->apierror([], '请确认送达', 0);
                        }
                        if (request()->user->type != 1) {
                            return $this->apierror([], '非管理员无完结权限', 0);
                        }
                        $post['complete_time'] = time();
                        break;
                    case '7':
                        if (request()->user->type == 2 && $order['status'] >= 2) {
                            return $this->apierror([], '订单已处于您不可取消状态，如需取消请联系管理员', 0);
                        }
                        if (request()->user->type == 0 || request()->user->type >= 3) {
                            return $this->apierror([], '无取消订单权限，如需取消请联系管理员', 0);
                        }
                        $post['cacel_time'] = time();
                        break;
                    default:
                        return $this->apierror([], '操作状态错误', 0);
                        break;
                }
                Db::startTrans();
                try {
                    //确认订单库存操作
                    if ($post['status'] == 2) {
                        $products = (new PutorderProduct())->where('orderid', $order['id'])->select();
                        foreach ($products as $product) {
                            if ($order['type'] == 1) {
                                (new ProductLog())->ProductSkuEdit($product['goodsid'], -$product['number'], 1, '订单' . $order['id'] . '确认扣除库存', request()->user->id);
                            } else {
                                (new ProductLog())->ProductSkuEdit($product['goodsid'], $product['number'], 1, '订单' . $order['id'] . '退单确认增加库存', request()->user->id);
                            }
                        }
                    }
                    //取消订单库存操作
                    if ($post['status'] == 7 && $order['status'] >= 2) {
                        $products = (new PutorderProduct())->where('orderid', $order['id'])->select();
                        foreach ($products as $product) {
                            if ($order['type'] == 1) {
                                (new ProductLog())->ProductSkuEdit($product['goodsid'], $product['number'], 1, '订单' . $order['id'] . '取消返还库存', request()->user->id);
                            } else {
                                (new ProductLog())->ProductSkuEdit($product['goodsid'], -$product['number'], 1, '退单类型订单' . $order['id'] . '取消扣除库存', request()->user->id);
                            }
                        }
                    }
                    Putorder::update($post);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    return $this->apierror([], $e->getMessage(), 0);
                }
                return $this->apisuccess([], '操作成功', 0);
            }
        }
    }

    public function getorder()
    {
        $page  = (int)input('page', 1);
        $limit = (int)input('limit', 20);
        $keyswords  = input('keyswords');
        $status  = input('status');
        $where = [];
        if (!empty($keyswords)) {
            $where[] = ['mobile|name', 'like', '%' . $keyswords . '%'];
        }
        if (request()->user->type == 2) {
            $where[] = ['user_id', '=', request()->user->id];
        } elseif (request()->user->type == 3) {
            $where[] = ['ouser_id', '=', request()->user->id];
        } elseif (request()->user->type == 1) {
        } else {
            $where[] = ['id', '=', 0];
        }
        if (!empty($status)) {
            if ($status == -1) {
                $where[] = ['status', 'in', [2, 3, 4, 5]];
            } else {
                $where[] = ['status', '=', $status];
            }
        }
        $count = (new Putorder())->where($where)->count();
        $list = (new Putorder())->where($where)->order(['allocate_time' => 'desc','id' => 'desc'])->limit($limit)
            ->page($page)->select();
        foreach ($list as $row) {
            $row['send_name'] = '';
            if ($row['send_type'] == 1) {
                $ouser = (new UserModel())->where('id', $row['ouser_id'])->find();
                $row['send_name'] = $ouser['name'] ?? '';
                $row['send_mobile'] = $ouser['mobile'] ?? '';
            } else {
                $row['send_name'] = $this->config['sendType'][$row['send_type']] ?? '未知';
            }
            //销售员信息
            $row['put_name'] = '';
            $row['put_mobile'] = '';
            $user = (new UserModel())->where('id', $row['user_id'])->find();
            if ($user) {
                $row['put_name'] = $user['name'];
                $row['put_mobile'] = $user['mobile'];
            }
            $row['status_text'] = $this->config['statusArr'][$row['status']] ?? '未知状态';
            $row['addjson'] = json_decode($row['addjson'], true);
            $product = (new PutorderProduct())->where('orderid', $row['id'])
                ->select()->each(function ($item) {
                    $item['images'] = json_decode($item['images'], true);
                    return $item;
                });
            $row['orderproduct'] = $product;
        }
        return $this->apisuccess($list, '获取成功', $count);
    }

    public function getorderdetail()
    {
        $id  = (int)input('id', 0);
        $order = (new Putorder())->where('id', $id)->find();
        if ($order) {
            //销售员信息
            $order['put_name'] = '';
            $order['put_mobile'] = '';
            $user = (new UserModel())->where('id', $order['user_id'])->find();
            if ($user) {
                $order['put_name'] = $user['name'];
                $order['put_mobile'] = $user['mobile'];
            }
            //师傅配送人信息
            $order['send_name'] = '';
            if ($order['send_type'] == 1) {
                $ouser = (new UserModel())->where('id', $order['ouser_id'])->find();
                $order['send_name'] = $ouser['name'] ?? '';
                $order['send_mobile'] = $ouser['mobile'] ?? '';
            } else {
                $order['send_name'] = $this->config['sendType'][$order['send_type']] ?? '未知';
            }
            $order['send_text'] = $this->config['sendType'][$order['send_type']] ?? '待分配';
            $order['status_text'] = $this->config['statusArr'][$order['status']] ?? '未知状态';
            $order['addjson'] = json_decode($order['addjson'], true);
            $order['images'] = json_decode($order['images'], true);
            $product = (new PutorderProduct())->where('orderid', $order['id'])
                ->select()->each(function ($item) {
                    $item['images'] = json_decode($item['images'], true);
                    return $item;
                });
            $order['orderproduct'] = $product;
        }
        $user = (new UserModel())->where(['type' => [2, 3]])->field('id,name,mobile')->select();
        return $this->apisuccess(['order' => $order, 'user' => $user], '获取成功');
    }


    /**
     * 用户下单
     * @return mixed|void
     */
    public function putorder()
    {
        if (request()->isPost()) {
            // 获取参数
            if (request()->isPost()) {
                $post = request()->post();
                $validate = (new Validate())->rule([
                    'goods' => 'require',
                    'type' => 'require',
                    'name' => 'require',
                    'mobile' => 'require',
                    'readdress' => 'require',
                    'lat' => 'require',
                    'lon' => 'require',
                    'address' => 'require',
                    'yjsd' => 'require',
                ]);
                $validate->message([
                    'goods.require' => '产品信息不能为空',
                    'type.require' => '下单类型不能为空',
                    'mobile.require' => '联系电话不能为空',
                    'name.require' => '客户姓名不能为空',
                    'readdress.require' => '所在地区不能为空',
                    'lat.require' => '所在地区坐标错误，请重试',
                    'lon.require' => '所在地区坐标错误，请重试',
                    'address.require' => '详细地址不能为空',
                    'yjsd.require' => '预估送达时间不能为空',
                ]);
                if (!$validate->check($post)) {
                    return $this->apierror([], $validate->getError(), 0);
                }
                foreach ($post['addjson'] as $k => $addjson) {
                    if (empty($addjson['lat']) || empty($addjson['lng']) || empty($addjson['name'])) {
                        return $this->apierror([], '第' . ($k + 1) . '行额外地址数据错误，请重新设置', 0);
                    }
                }
                $post['addjson'] = json_encode($post['addjson'] ?? [], true);
                $post['user_id'] = request()->user->id;
                $post['status'] = 1;
                $post['total'] = 0;
                foreach ($post['goods'] as $goods) {
                    $post['total'] += $goods['number'] * $goods['price'];
                }
                Db::startTrans();
                try {
                    $order = (new Putorder())->create($post);
                    foreach ($post['goods'] as $goods) {
                        $goods['images'] = json_encode($goods['images'] ?? [], true);
                        $goods['orderid'] = $order->id;
                        $goods['goodsid'] = $goods['id'];
                        unset($goods['id']);
                        (new PutorderProduct())->create($goods);
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    return $this->apierror([], $e->getMessage(), 0);
                }
                return $this->apisuccess([], '下单成功', 0);
            }
        }
    }

    /**
     * 手机用户登录
     * @return mixed|void
     */
    public function addAddress()
    {
        if (request()->isPost()) {
            // 获取参数
            if (request()->isPost()) {
                $post = request()->post();
                $validate = (new Validate())->rule([
                    'name' => 'require',
                    'mobile' => 'require',
                    'readdress' => 'require',
                    'lat' => 'require',
                    'lon' => 'require',
                    'address' => 'require',
                ]);
                $validate->message([
                    'mobile.require' => '联系电话不能为空',
                    'name.require' => '客户姓名不能为空',
                    'readdress.require' => '所在地区不能为空',
                    'lat.require' => '所在地区坐标错误，请重试',
                    'lon.require' => '所在地区坐标错误，请重试',
                    'address.require' => '详细地址不能为空',
                ]);
                if (!$validate->check($post)) {
                    return $this->apierror([], $validate->getError(), 0);
                }
                $post['addjson'] = json_encode($post['addjson'] ?? [], true);
                if (!empty($post['id'])) {
                    if (Kehu::update($post)) {
                        return $this->apisuccess([], '修改成功', 0);
                    }
                } else {
                    $post['user_id'] = request()->user->id;
                    if (Kehu::create($post)) {
                        return $this->apisuccess([], '添加成功', 0);
                    }
                }

                return $this->apierror([], '账号或密码错误', 0);
            }
        } else {
            $page  = (int)input('page', 1);
            $limit = (int)input('limit', 20);
            $title  = input('title');
            $where = [];
            if (!empty($title)) {
                $where[] = ['mobile|name', 'like', '%' . $title . '%'];
            }
            if (request()->user->type != 1) {
                $where[] = ['user_id', '=', request()->user->id];
            }
            $count = (new Kehu())->where($where)->count();
            $list = (new Kehu())->where($where)->order('id desc')->limit($limit)
                ->page($page)->select();
            foreach ($list as $row) {
                $row['addjson'] = json_decode($row['addjson'], true);
            }
            return $this->apisuccess($list, '获取成功', $count);
        }
    }
    /**
     * 手机用户登录
     * @return mixed|void
     */
    public function mlogin()
    {
        if (request()->isPost()) {
            // 获取参数
            if (request()->isPost()) {
                $post = request()->post();
                $validate = (new Validate())->rule([
                    'mobile' => 'require',
                    'password' => 'require',
                ]);
                $validate->message([
                    'mobile.require' => '账号不能为空',
                    'password.require' => '密码不能为空',
                ]);
                if (!$validate->check($post)) {
                    return $this->apierror([], $validate->getError(), 0);
                }
                $user = (new UserModel())->where(['mobile' => $post['mobile'], 'password' => md5(md5($post['password'])), 'isdel' => 1])->find();
                if ($user) {
                    // 更新登录数据
                    $update = [
                        'id'          => $user['id'],
                        'login_time'  => time(),
                        'login_ip'    => request()->getRealIp(),
                        'login_count' => $user['login_count'] + 1,
                    ];
                    if (UserModel::update($update)) {
                        Event::emit('userLoginSuccess', $user);
                        $token = md5(Random::alpha(16) . $user['id']);
                        Cache::set($token, $user->id);
                        return $this->apisuccess(['token' => $token], '登陆成功', 0);
                    }
                }
                return $this->apierror([], '账号或密码错误', 0);
            }
        }
    }

    /**
     * 微信用户登录
     * @return mixed|void
     */
    public function login()
    {
        if (request()->isPost()) {
            // 获取参数
            $config = [
                'app_id' => 'wxbbb4f2d54c996168',
                'secret' => '94a849a9d6c59e04f539d7982e9eaf1c',
            ];
            $code = input('code');
            $app = Factory::miniProgram($config);
            try {
                $res = $app->auth->session($code);
                //查找是否注册等操作
                if ($res['openid']) {
                    // 更新登录数据
                    $UserThird = (new UserModel())->where(['openid' => $res['openid'], 'isdel' => 1])->find();
                    if (empty($UserThird)) {
                        //注册用户
                        $update = [
                            'login_time'  => time(),
                            'login_ip'    => request()->getRealIp(),
                            'nickname' => '用户' . time(),
                            'avatar' => '',
                            'openid' => $res['openid']
                        ];
                        Db::startTrans();
                        try {
                            $user = (new UserModel())->create($update);
                            $token = md5(Random::alpha(16) . $user['id']);
                            Cache::set($token, $user->id);
                            Db::commit();
                        } catch (\Exception $e) {
                            Db::rollback();
                            return $this->apierror([], $e->getMessage(), 0);
                        }
                    } else {
                        // 更新登录数据
                        $update = [
                            'id'          => $UserThird['id'],
                            'login_time'  => time(),
                            'login_ip'    => request()->getRealIp(),
                            'login_count' => $UserThird['login_count'] + 1,
                        ];
                        if (UserModel::update($update)) {
                            $token = md5(Random::alpha(16) . $UserThird['id']);
                            Cache::set($token, $UserThird->id);
                        }
                    }
                }
            } catch (\Exception $e) {
                return $this->apierror([], $e->getMessage(), 0);
            }
            if (!empty($token)) {
                return $this->apisuccess(['token' => $token], '登陆成功', 0);
            } else {
                return $this->apierror([], '登陆失败，请重试', 0);
            }
        }
    }


    /**
     * 文件上传
     */
    public function getinfo()
    {
        $user = request()->user;
        if (empty($user['name'])) {
            $user['name'] = '无';
        }
        unset($user['openid']);
        unset($user['password']);
        return $this->apisuccess($user, '获取成功', 0);
    }

    /**
     * 文件上传
     */
    public function saveinfo()
    {
        if (request()->isPost()) {
            $post = request()->post();
            if (empty($post['avatar']) && empty($post['nickname']) && empty($post['iv'])) {
                return $this->apierror([], '资料参数不能为空', 0);
            }
            if (!empty($post['avatar'])) {
                // 更新登录数据
                $update = [
                    'id' => request()->user->id,
                    'avatar'  => $post['avatar'],
                ];
                if (UserModel::update($update)) {
                    return $this->apisuccess([], '设置成功', 0);
                }
            }
            if (!empty($post['nickname'])) {
                // 更新登录数据
                $update = [
                    'id' => request()->user->id,
                    'nickname'  => $post['nickname'],
                ];
                if (UserModel::update($update)) {
                    return $this->apisuccess([], '设置成功', 0);
                }
            }
            if (!empty($post['iv'])) {
                // 更新登录数据
                $config = [
                    'app_id' => 'wxbbb4f2d54c996168',
                    'secret' => '94a849a9d6c59e04f539d7982e9eaf1c',
                ];
                $app = Factory::miniProgram($config);
                try {
                    $res = $app->auth->session($post['code'] ?? '');
                } catch (\Exception $e) {
                    return $this->apierror([], '获取手机号失败', 0);
                }
                if (empty($res['session_key'])) {
                    return $this->apierror([], '获取微信key失败', 0);
                }
                try {
                    $decryptedData = $app->encryptor->decryptData($res['session_key'], $post['iv'], $post['encryptedData']);
                } catch (\Exception $e) {
                    return $this->apierror([], $e->getMessage(), 0);
                }
                if (!empty($decryptedData['purePhoneNumber'])) {
                    // 更新登录数据
                    $update = [
                        'id' => request()->user->id,
                        'mobile'  => $decryptedData['purePhoneNumber'],
                    ];
                    if (UserModel::update($update)) {
                        return $this->apisuccess([], '设置成功', 0);
                    }
                }
            }
            return $this->apierror([], '设置失败', 0);
        }
    }

    /**
     * 文件上传
     */
    public function upload()
    {
        if (request()->isPost()) {
            $file = Upload::instance()->upload();
            if (!$file) {
                return $this->apierror([], Upload::instance()->getError(), 0);
            }
            return $this->apisuccess($file['url'], '登陆成功', 0);
        }
    }
}
